package cn.dancepeak.user.service.impl;

import cn.dancepeak.anno.Log;
import cn.dancepeak.exception.BusinessException;
import cn.dancepeak.user.domain.User;
import cn.dancepeak.user.mapper.UserMapper;
import cn.dancepeak.user.query.UserQuery;
import cn.dancepeak.user.service.IUserServiceImpl;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImplImpl implements IUserServiceImpl {
    @Autowired
    private UserMapper userMapper;
    @Override
    @Log
    public void add(User user) {
        //判断是否注册过
        User user1 = userMapper.selectByUsername(user.getUserName());
        if(ObjectUtil.isNotNull(user1)){
            throw new BusinessException("用户已被注册");
        }
        //密码新增以后要加密
        userMapper.insert(user);
    }

    @Override
    @Log
    public void update(User user) {
        //用户名不能修改   禁用  在前端写
        userMapper.updateById(user);
    }

    @Override
    @Log
    public void delete(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    @Log
    public void deleteByList(List<Long> ids) {
        userMapper.deleteByList(ids);
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public PageInfo<User> page(UserQuery userQuery) {
        // 1.下面这句代码表示开启分页，会将紧挨着这句代码的下一次数据库执行进行分页，切记一定要放在要分页的SQL语句前面执行
        // 2.执行SQL语句带条件查询，SQL语句不需要进行分页
        PageHelper.startPage(userQuery.getCurrentPage(), userQuery.getPageSize());
        List<User> user = userMapper.list(userQuery);
        // 3.将查询结果转换为PageInfo对象，PageInfo对象中有前端分页所需要的各种参数
        PageInfo<User> pageInfo = new PageInfo<>(user);
        // 4.响应总条数和分页信息
        return pageInfo;
    }
}
